package com.max.view;

import com.alibaba.fastjson.JSON;
import com.max.entity.UserMessage;
import com.max.service.UserMessageService;
import com.max.service.UserinfoService;
import com.max.socket.dto.MsgDTO;
import com.max.socket.dto.MsgType;

import javax.swing.*;
import java.awt.*;
import java.io.PrintWriter;
import java.util.List;
import java.util.function.Consumer;

public class ChatWindow extends JFrame {

    public ChatWindow(PrintWriter writer, String username, Consumer<Consumer<MsgDTO>> consumer) {
        setTitle("群聊");
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());

        Font font = new Font("微软雅黑", Font.PLAIN, 14);

        JTextArea textArea = new JTextArea();
        textArea.setEditable(false);
        textArea.setFont(font);
        textArea.setBackground(new Color(245, 245, 245));
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewportView(textArea);

        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new BorderLayout());
        JTextField inputField = new JTextField();
        inputField.setFont(font);
        inputPanel.add(inputField, BorderLayout.CENTER);
        JButton sendButton = new JButton("发送");
        sendButton.addActionListener(e -> {
            String message = inputField.getText().trim();
            textArea.append("我：" + message + "\n");
            inputField.setText("");
            MsgDTO msgDTO = new MsgDTO(MsgType.MSG, message, username);
            writer.println(JSON.toJSONString(msgDTO));
        });

        inputPanel.add(sendButton, BorderLayout.EAST);
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        mainPanel.add(inputPanel, BorderLayout.SOUTH);

        //加载历史消息
        List<UserMessage> userMessages = UserMessageService.getInstance().selectMessageListOrderByTime();
        for (UserMessage userMessage : userMessages) {
            boolean isMe = username.equals(userMessage.getUsername());
            textArea.append((isMe ? "我" : userMessage.getUsername()) + "：" + userMessage.getMessageContent() + "\n");
        }

        consumer.accept(msg -> {
            textArea.append(msg.getSender() + "：" + msg.getContent() + "\n");
        });

        setContentPane(mainPanel);
        setVisible(true);

    }


//    public static void main(String[] args) {
//        new ChatWindow();
//    }


}
